package com.zy.webSocket;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @author 张宇
 * @date 2021/6/9 14:46
 */
@Slf4j
@Component
public class MessageHandshakeInterceptor implements HandshakeInterceptor
{

    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest,ServerHttpResponse serverHttpResponse,
                                   WebSocketHandler webSocketHandler,Map<String, Object> map) throws Exception
    {
        String path = serverHttpRequest.getURI().getPath();
        log.debug("URL:"+path);
        String[] ss = StringUtils.split(path,'/');
        if(ss.length != 3)
        {
            return false;
        }
        if(!StringUtils.isNumeric(ss[2]))
        {
            return false;
        }
        map.put("uid",Long.valueOf(ss[2]));
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest,ServerHttpResponse serverHttpResponse,
                               WebSocketHandler webSocketHandler,Exception e)
    {
        log.debug("握手成功!");
    }

}
